﻿using System;
using System.Collections.Generic;
using System.Drawing.Design;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;

using Aliphant.Common;
using Aliphant.Common.Helper;
using Aliphant.UI;
using Aliphant.UI.Forms.Notify;
using Aliphant.UI.Windows;

using Microsoft.Web.WebView2.Core;

namespace TestModule.Widgets
{
    /// <summary>
    /// WidgetBrowser.xaml 的交互逻辑
    /// </summary>
    public partial class WidgetBrowser : UserControl, IWidget
    {
        private bool isLoad = false;
        private bool settingStatus = false;

        private Dictionary<string, string> collectedList = new Dictionary<string, string>();
        private Stack<string> lastHistoryStack = new Stack<string>();
        private Stack<string> nextHistoryStack = new Stack<string>();
        private string currentUrl;
        private string homePageUrl;
        private bool isFromWebView = false;

        private Widget? widget;

        public WidgetBrowser(string url)
        {
            InitializeComponent();
            InitializeWebView2();

            webView.Source = new Uri(url);
            urlInput.Text = webView.Source.ToString();
            currentUrl = webView.Source.ToString();
            homePageUrl = url;
        }

        private async void InitializeWebView2()
        {
            var userDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XDeskTool/WebView2Data");

            var env = await CoreWebView2Environment.CreateAsync(
                browserExecutableFolder: null,
                userDataFolder: userDataFolder
            );
            // 关键：必须在设置 Source 前初始化环境
            await webView.EnsureCoreWebView2Async(env);
        }

        private async void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!isLoad)
            {
                isLoad = true;
                await LoadWebView();

                winSizeCmbox.Items.Add(new ComboBoxItem() { Content = "480 * 270" });
                winSizeCmbox.Items.Add(new ComboBoxItem() { Content = "300 * 150" });
                winSizeCmbox.Items.Add(new ComboBoxItem() { Content = "300 * 200" });
                winSizeCmbox.Items.Add(new ComboBoxItem() { Content = "400 * 300" });
                winSizeCmbox.Items.Add(new ComboBoxItem() { Content = "720 * 405" });
                winSizeCmbox.Items.Add(new ComboBoxItem() { Content = "960 * 540" });
                winSizeCmbox.SelectedIndex = 0;

                LoadCollectedList();
                UpdateCollectedList();
            }
        }

        /// <summary>
        /// 初始化WebView
        /// </summary>
        /// <returns></returns>
        private async Task LoadWebView()
        {
            if (webView.CoreWebView2 == null)
            {
                await webView.EnsureCoreWebView2Async().ContinueWith(_ =>
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        if (webView.CoreWebView2 != null)
                        {
                            webView.SourceChanged += WebView_SourceChanged;
                            webView.CoreWebView2.NavigationCompleted += CoreWebView2_NavigationCompleted;
                        }
                    });
                });

                if (webView.CoreWebView2 != null)
                {
                    webView.CoreWebView2.NewWindowRequested += OnNewWindowRequest;  // 拦截打开新Web窗口请求
                }

            }
        }

        private void CoreWebView2_NavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            if (e.IsSuccess)
            {
                string css = @"
            ::-webkit-scrollbar {
                width: 12px;          /* 滚动条宽度 */
                background: #262626;  /* 轨道背景色 */
            }
            ::-webkit-scrollbar-thumb {
                background: #323232;      /* 滑块颜色 */
                border-radius: 6px;    /* 圆角 */
            }
            ::-webkit-scrollbar-thumb:hover {
                background: #555;      /* 悬停效果 */
            }
        ";
                // 注入CSS
                webView.CoreWebView2.ExecuteScriptAsync(
                    $"var style=document.createElement('style');style.innerHTML=`{css}`;document.head.appendChild(style);"
                );
            }
        }

        private void WebView_SourceChanged(object? sender, CoreWebView2SourceChangedEventArgs e)
        {
            urlInput.Text = webView.Source.ToString();
            AddHistory(webView.Source.ToString(), isFromWebView);

            currentUrl = webView.Source.ToString();
        }


        /// <summary>
        /// 新Web窗口请求
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnNewWindowRequest(object? sender, CoreWebView2NewWindowRequestedEventArgs e)
        {
            var deferral = e.GetDeferral();
            e.NewWindow = this.webView.CoreWebView2;
            deferral.Complete();
        }


        public void Init(Widget widget)
        {
            this.widget = widget;
            margingss.Text = widget.RightMargin.ToString();
        }

        public string? QuickButton1Tip => "激活窗口";

        public string? QuickButton2Tip => "设置";


        public string? QucikButton1Icon => "Icon.TriangleRight";

        public string? QucikButton2Icon => "Icon.Setting";

        public void SetScriptPath(string scriptPath)
        {

        }

        public void QuickAction1()
        {

        }

        public void QuickAction2()
        {
            // 开关/设置

            if (settingStatus)
            {
                settingStatus = false;
                settings.Visibility = Visibility.Collapsed;
            }
            else
            {
                settingStatus = true;
                settings.Visibility = Visibility.Visible;
            }
        }

        public void Close()
        {
            SaveCollectedList();
        }

        /// <summary>
        /// 窗口尺寸更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void winSizeCmbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var combo = (ComboBox)sender;
            if (combo == null)
            {
                return;
            }
            var selected = combo.SelectedItem as ComboBoxItem;
            if (selected == null)
            {
                return;
            }
            string? content = selected.Content.ToString();
            if (string.IsNullOrEmpty(content))
            {
                return;
            }

            string[] strs = content.Split('*');
            double width = double.Parse(strs[0].Trim());
            double height = double.Parse(strs[1].Trim());

            webView.Width = width;
            webView.Height = height;
        }

        /// <summary>
        /// 地址跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchUrl(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(urlInput.Text))
            {
                return;
            }
            try
            {
                isFromWebView = false;
                webView.Source = new Uri(urlInput.Text);
                AddHistory(webView.Source.ToString(), true);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

        /// <summary>
        /// 收藏夹选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void collectedCmbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var combo = (ComboBox)sender;
            if (combo == null)
            {
                return;
            }
            var selected = combo.SelectedItem as ComboBoxItem;
            if (selected == null)
            {
                return;
            }
            string? content = selected.Content.ToString();
            if (string.IsNullOrEmpty(content))
            {
                return;
            }

            collectedList.TryGetValue(content, out string? url);
            if (url == null)
            {
                return;
            }

            isFromWebView = false;
            webView.Source = new Uri(url);
            AddHistory(webView.Source.ToString(), true);
            combo.SelectedIndex = -1;
        }

        private void LoadCollectedList()
        {
            string file = DomainHelper.GetHistoryPath("broswer.json", "collected");
            JsonHelper.ReadJson<Dictionary<string, string>>(file, out Dictionary<string, string>? list);
            if (list != null)
            {
                collectedList = list;
            }
        }

        private void SaveCollectedList()
        {
            string file = DomainHelper.GetHistoryPath("broswer.json", "collected");
            JsonHelper.SaveToJson<Dictionary<string, string>>(ref collectedList, file);
        }

        private void UpdateCollectedList()
        {
            collectedCmbox.Items.Clear();
            foreach (var item in collectedList)
            {
                collectedCmbox.Items.Add(new ComboBoxItem() { Content = item.Key });
            }
        }

        private void Collected(object sender, RoutedEventArgs e)
        {
            string title = webView.CoreWebView2.DocumentTitle;
            string url = webView.Source.ToString();
            collectedList.Add(title, url);
            UpdateCollectedList();

            NotifyIconHelper.ShowBalloon("收藏成功");
        }

        private void DeleteCollected(object sender, RoutedEventArgs e)
        {
            string title = webView.CoreWebView2.DocumentTitle;
            if (collectedList.ContainsKey(title))
            {
                collectedList.Remove(title);
                UpdateCollectedList();
            }
        }

        private void LastPage(object sender, RoutedEventArgs e)
        {
            if (lastHistoryStack.Count <= 0)
            {
                return;
            }

            // 当前页面放入Next栈
            nextHistoryStack.Push(currentUrl);

            // 从Last栈顶取出页面
            string url = lastHistoryStack.Pop();
            isFromWebView = false;
            webView.Source = new Uri(url);
            currentUrl = url;
        }

        private void NextPage(object sender, RoutedEventArgs e)
        {
            if (nextHistoryStack.Count <= 0)
            {
                return;
            }

            // 当前页面放入Last栈
            lastHistoryStack.Push(currentUrl);

            // 从Next栈顶取出页面
            string url = nextHistoryStack.Pop();
            isFromWebView = false;
            webView.Source = new Uri(url);
            currentUrl = url;
        }

        private void HomePage(object sender, RoutedEventArgs e)
        {
            lastHistoryStack.Push(currentUrl);
            webView.Source = new Uri(homePageUrl);
            currentUrl = homePageUrl;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="isNew">是否是新页面</param>
        private void AddHistory(string url, bool isNew)
        {
            if (isNew)
            {
                nextHistoryStack.Clear();
                lastHistoryStack.Push(currentUrl);
            }
            isFromWebView = true;
        }

        private void margingss_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (double.TryParse(((TextBox)sender).Text, out double value) && widget != null)
            {
                widget.RightMargin = value;
            }
        }
    }
}
